# 用户创建API增强
# 文件路径: backend/api/user_creation_api.py
# 功能: 支持批量用户创建和密码验证

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from werkzeug.security import generate_password_hash
import re
from datetime import datetime

from backend.models import db, User, Role

user_creation_bp = Blueprint('user_creation', __name__)

def validate_password_strength(password):
    """验证密码强度"""
    if not password:
        return False, ["密码不能为空"]
    
    messages = []
    strength = 0
    
    # 长度检查
    if len(password) < 6:
        messages.append("密码长度至少6位")
    else:
        strength += 1
    
    # 包含数字
    if re.search(r'\d', password):
        strength += 1
    else:
        messages.append("密码应包含数字")
    
    # 包含字母
    if re.search(r'[a-zA-Z]', password):
        strength += 1
    else:
        messages.append("密码应包含字母")
    
    # 包含特殊字符
    if re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
        strength += 1
    elif len(password) >= 8:
        messages.append("建议包含特殊字符以增强安全性")
    
    is_valid = strength >= 2 and len(password) >= 6
    return is_valid, messages

def validate_user_data(data):
    """验证用户数据"""
    errors = []
    
    # 必填字段检查
    if not data.get('username'):
        errors.append("用户名不能为空")
    
    if not data.get('password'):
        errors.append("密码不能为空")
    
    # 用户名格式检查
    username = data.get('username', '')
    if username:
        if len(username) < 3:
            errors.append("用户名长度至少3位")
        if not re.match(r'^[a-zA-Z0-9_]+$', username):
            errors.append("用户名只能包含字母、数字和下划线")
    
    # 密码强度检查
    password = data.get('password', '')
    if password:
        is_valid, messages = validate_password_strength(password)
        if not is_valid:
            errors.extend(messages)
    
    # 邮箱格式检查
    email = data.get('email', '')
    if email and not re.match(r'^[^\s@]+@[^\s@]+\.[^\s@]+$', email):
        errors.append("邮箱格式不正确")
    
    # 手机号格式检查
    mobile = data.get('mobile', '')
    if mobile and not re.match(r'^1[3-9]\d{9}$', mobile):
        errors.append("手机号格式不正确")
    
    return errors

@user_creation_bp.route('/api/users/create', methods=['POST'])
@jwt_required()
def create_user():
    """创建单个用户"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        if not data:
            return jsonify({
                'success': False,
                'message': '请提供用户数据'
            }), 400
        
        # 验证数据
        errors = validate_user_data(data)
        if errors:
            return jsonify({
                'success': False,
                'message': '数据验证失败',
                'errors': errors
            }), 400
        
        # 检查用户名是否已存在
        existing_user = User.query.filter_by(username=data['username']).first()
        if existing_user:
            return jsonify({
                'success': False,
                'message': '用户名已存在'
            }), 400
        
        # 检查邮箱是否已存在
        if data.get('email'):
            existing_email = User.query.filter_by(email=data['email']).first()
            if existing_email:
                return jsonify({
                    'success': False,
                    'message': '邮箱已被使用'
                }), 400
        
        # 检查手机号是否已存在
        if data.get('mobile'):
            existing_mobile = User.query.filter_by(mobile=data['mobile']).first()
            if existing_mobile:
                return jsonify({
                    'success': False,
                    'message': '手机号已被使用'
                }), 400
        
        # 创建用户
        user = User(
            username=data['username'],
            password_hash=generate_password_hash(data['password']),
            real_name=data.get('real_name', ''),
            mobile=data.get('mobile', ''),
            email=data.get('email', ''),
            gender=data.get('gender', ''),
            department=data.get('department', ''),
            position=data.get('position', ''),
            address=data.get('address', ''),
            user_type=data.get('user_type', 'web'),
            status=data.get('status', 'active'),
            remark=data.get('remark', ''),
            created_at=datetime.utcnow(),
            created_by=current_user_id
        )
        
        # 分配角色
        roles = data.get('roles', [])
        if isinstance(roles, str):
            roles = [roles]
        
        for role_name in roles:
            role = Role.query.filter_by(name=role_name).first()
            if role:
                user.roles.append(role)
        
        # 如果没有指定角色，分配默认角色
        if not user.roles:
            default_role = Role.query.filter_by(name='guest').first()
            if default_role:
                user.roles.append(default_role)
        
        db.session.add(user)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '用户创建成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'real_name': user.real_name,
                'status': user.status
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'创建用户失败: {str(e)}'
        }), 500

@user_creation_bp.route('/api/users/batch-create', methods=['POST'])
@jwt_required()
def batch_create_users():
    """批量创建用户"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        if not data or not data.get('users'):
            return jsonify({
                'success': False,
                'message': '请提供用户数据列表'
            }), 400
        
        users_data = data['users']
        results = {
            'success': 0,
            'failed': 0,
            'errors': [],
            'created_users': []
        }
        
        for i, user_data in enumerate(users_data, 1):
            try:
                # 验证数据
                errors = validate_user_data(user_data)
                if errors:
                    results['failed'] += 1
                    results['errors'].append(f'第{i}行: {", ".join(errors)}')
                    continue
                
                # 检查重复
                existing_user = User.query.filter_by(username=user_data['username']).first()
                if existing_user:
                    results['failed'] += 1
                    results['errors'].append(f'第{i}行: 用户名已存在')
                    continue
                
                if user_data.get('email'):
                    existing_email = User.query.filter_by(email=user_data['email']).first()
                    if existing_email:
                        results['failed'] += 1
                        results['errors'].append(f'第{i}行: 邮箱已被使用')
                        continue
                
                # 创建用户
                user = User(
                    username=user_data['username'],
                    password_hash=generate_password_hash(user_data['password']),
                    real_name=user_data.get('real_name', ''),
                    mobile=user_data.get('mobile', ''),
                    email=user_data.get('email', ''),
                    gender=user_data.get('gender', ''),
                    department=user_data.get('department', ''),
                    position=user_data.get('position', ''),
                    user_type=user_data.get('user_type', 'web'),
                    status=user_data.get('status', 'active'),
                    created_at=datetime.utcnow(),
                    created_by=current_user_id
                )
                
                # 分配角色
                roles = user_data.get('roles', [])
                if isinstance(roles, str):
                    roles = [roles]
                
                for role_name in roles:
                    role = Role.query.filter_by(name=role_name).first()
                    if role:
                        user.roles.append(role)
                
                if not user.roles:
                    default_role = Role.query.filter_by(name='guest').first()
                    if default_role:
                        user.roles.append(default_role)
                
                db.session.add(user)
                db.session.flush()  # 获取ID但不提交
                
                results['success'] += 1
                results['created_users'].append({
                    'id': user.id,
                    'username': user.username,
                    'real_name': user.real_name
                })
                
            except Exception as e:
                results['failed'] += 1
                results['errors'].append(f'第{i}行: {str(e)}')
                db.session.rollback()
        
        # 提交所有成功的创建
        if results['success'] > 0:
            db.session.commit()
        
        return jsonify({
            'success': True,
            'message': f'批量创建完成，成功{results["success"]}个，失败{results["failed"]}个',
            'data': results
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'批量创建用户失败: {str(e)}'
        }), 500

@user_creation_bp.route('/api/users/validate-password', methods=['POST'])
def validate_password():
    """验证密码强度（无需登录）"""
    try:
        data = request.get_json()
        password = data.get('password', '')
        
        is_valid, messages = validate_password_strength(password)
        
        # 计算强度分数
        strength = 0
        if len(password) >= 6:
            strength += 1
        if re.search(r'\d', password):
            strength += 1
        if re.search(r'[a-zA-Z]', password):
            strength += 1
        if re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
            strength += 1
        
        strength_labels = ['很弱', '弱', '中等', '强', '很强']
        strength_colors = ['danger', 'warning', 'info', 'success', 'success']
        
        return jsonify({
            'success': True,
            'data': {
                'is_valid': is_valid,
                'strength': strength,
                'strength_text': strength_labels[strength] if strength < len(strength_labels) else '很弱',
                'strength_color': strength_colors[strength] if strength < len(strength_colors) else 'danger',
                'messages': messages
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'密码验证失败: {str(e)}'
        }), 500

@user_creation_bp.route('/api/users/check-availability', methods=['POST'])
def check_availability():
    """检查用户名、邮箱、手机号可用性"""
    try:
        data = request.get_json()
        
        result = {
            'username': {'available': True, 'message': ''},
            'email': {'available': True, 'message': ''},
            'mobile': {'available': True, 'message': ''}
        }
        
        # 检查用户名
        username = data.get('username')
        if username:
            existing_user = User.query.filter_by(username=username).first()
            if existing_user:
                result['username'] = {'available': False, 'message': '用户名已存在'}
        
        # 检查邮箱
        email = data.get('email')
        if email:
            existing_email = User.query.filter_by(email=email).first()
            if existing_email:
                result['email'] = {'available': False, 'message': '邮箱已被使用'}
        
        # 检查手机号
        mobile = data.get('mobile')
        if mobile:
            existing_mobile = User.query.filter_by(mobile=mobile).first()
            if existing_mobile:
                result['mobile'] = {'available': False, 'message': '手机号已被使用'}
        
        return jsonify({
            'success': True,
            'data': result
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'检查可用性失败: {str(e)}'
        }), 500
